
<template>
  <div class="bh-tree-container">
    <div class="search">
      <a-input v-model="searchKey" placeholder="搜索名称/编码" allow-clear>
        <template #prefix><icon-search /></template>
      </a-input>
      <a-button v-permission="['sys:config:add']" type="primary" @click="onAdd">
        <template #icon><icon-plus /></template>
      </a-button>
    </div>
    <div class="tree-wrapper">
      <div class="tree">
        <a-tree
            :data="(treeData as unknown as TreeNodeData[])"
            :field-names="{ key: 'id' }"
            block-node
            :selected-keys="selectedKeys"
            @select="select"
        >
          <template #title="node">
            <a-typography-paragraph
                :ellipsis="{
                rows: 1,
                showTooltip: true,
                css: true,
              }"
            >
              {{ node.name }} ({{ node.code }})
            </a-typography-paragraph>
          </template>
          <template #extra="node">
            <a-trigger trigger="click" align-point animation-name="slide-dynamic-origin" auto-fit-transform-origin position="bl" scroll-to-close>
              <icon-more-vertical  class="action" />
              <template #content>
                <RightMenu :data="node" @on-menu-item-click="onMenuItemClick" />
              </template>
            </a-trigger>
          </template>
        </a-tree>
      </div>
    </div>
    <DictFrom ref="ModalRef" @restart="()=>getTreeData()" />
  </div>
</template>
<script setup lang="ts">
import RightMenu from './menu.vue'
import DictFrom from './from.vue';
import type { TreeNodeData } from '@arco-design/web-vue'
import { mapTree } from 'xe-utils'
import  { type QueryResponse ,getList,deleteRows} from '@/api/system/config'
import { Message, Modal } from '@arco-design/web-vue'

import useLoading from '@/hooks/loading';

const { loading, setLoading } = useLoading();

const ModalRef = ref()
const searchKey = ref('')
const dataList = ref<TreeItem[]>([])

onMounted(() => {
  getTreeData()
})
const emit = defineEmits<{
  (e: 'node-click', keys: Array<any>): void
}>()


interface TreeItem extends QueryResponse {
  popupVisible: boolean
}


const selectedKeys = ref()
// 选中节点
const select = (keys: Array<any>) => {
  if (selectedKeys.value && selectedKeys.value[0] === keys[0]) {
    return
  }
  selectedKeys.value = keys
  emit('node-click', keys)
}
// 查询树列表
const getTreeData = async () => {
  try {
    setLoading(true)
    const { data } = await getList({})

    dataList.value = mapTree(data, (i) => ({
      ...i,
      popupVisible: false,
      icon: () => {
        return null
      },
    }))
    await nextTick(() => {
      select([dataList.value[0]?.id])
    })
  } finally {
    setLoading(false)
  }
}
const search = (keyword: string) => {
  const loop = (data: TreeItem[]) => {
    const result = [] as TreeItem[]
    data.forEach((item: TreeItem) => {
      if (item.name?.toLowerCase().includes(keyword) || item.code?.toLowerCase().includes(keyword)) {
        result.push({ ...item })
      }
    })
    return result
  }
  return loop(dataList.value)
}

const treeData = computed(() => {
  if (!searchKey.value) return dataList.value
  return search(searchKey.value.toLowerCase())
})

//新增
const onAdd = () => {
  ModalRef.value?.openAdd()
}

// 点击菜单项
const onMenuItemClick = (mode: string, node: QueryResponse) => {
  if (mode === 'update') {
    ModalRef.value?.openUpdate(node)
  } else if (mode === 'delete') {
    Modal.warning({
      title: '提示',
      content: `是否确定删除 [${node.name}]？`,
      hideCancel: false,
      okButtonProps: { status: 'danger' },
      onBeforeOk: async () => {
        try {
          await deleteRows(node.id)
          Message.success('删除成功')
          await getTreeData()
          return true
        } catch (error) {
          return false
        }
      },
   })
  }
}
</script>

<style scoped lang="less">
.tree-wrapper::-webkit-scrollbar{
 width: 6px;
  height: 4px;
}
.tree-wrapper::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: #fff;
}
.tree-wrapper::-webkit-scrollbar-track {
  border-radius: 10px;
  background: #fff;
}
.tree-wrapper:hover {
  &::-webkit-scrollbar-thumb {
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #d7d8dd;
  }
  &::-webkit-scrollbar-track {
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #fff;
  }
}
.tree-wrapper {
  flex: 1;
  overflow-y: auto;
  background-color: var(--color-bg-1);
  position: relative;
  height: 100%;
  margin-bottom:10px;
  .tree {
    flex: 1;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    overflow: auto
  }
}
:deep(.arco-tree-node) {
  line-height: normal;
  border-radius: var(--border-radius-medium);
  margin: 5px 0;
  .action {
    opacity: 0;
  }
  &:hover {
    background-color: var(--color-secondary-hover);
    .action {
      opacity: 1;
    }
  }

  .arco-tree-node-switcher {
    width: 0;
    margin-right: 0;
  }

  .arco-tree-node-title {
    position: relative;
    display: flex;
    align-items: center;
    margin-left: -4px;
    padding: 10px 4px;
    font-size: 14px;
    &:hover {
      background-color: transparent;
    }
  }

  .arco-tree-node-title-text {
    width: 100%;
    white-space: normal;
    overflow-wrap: anywhere;
  }
}

:deep(.arco-tree-node-selected) {
  font-weight: bold;
  background-color: rgba(var(--primary-6), 0.1);
  &:hover {
    background-color: rgba(var(--primary-6), 0.1);
  }
  .arco-typography {
    color: rgb(var(--primary-6));
    margin-bottom: 0;
  }
}


</style>